import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.test.context.SpringBootTest;

import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description : bean properties util
 * @Author : guxuemin
 * @Version : V1.0.0
 * @Date : 2021/11/10 10:51
 */
@SpringBootTest
@Slf4j
public class BeanUtilT {

    /**
     * 获取对象属性
     *
     * @param obj  对象
     * @param name 属性名
     */
    public static Object getObjProperties(Object obj, String name) throws Exception {
        try {
            PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(obj.getClass(), name);
            if (propertyDescriptor != null) {
                return propertyDescriptor.getReadMethod().invoke(obj);
            }
            return null;
        } catch (Exception e) {
            log.error("Object get properties error", e);
            throw new Exception("get properties error");
        }
    }

    public static <T> List<T> getList(Object likes) {
        List<T> likeList = null;
        if (likes instanceof List) {
            likeList = Convert.convert(new TypeReference<List<T>>() {
            }, likes);
        }
        return likeList;
    }

    public static void main(String[] args) throws Exception {
        Student student = new Student();
        student.setLike(Arrays.asList("movies", "sport", "work"));
        student.setAge(Arrays.asList(1, 3, 9, 6, 8));
        student.setName("wh");
        student.setTeatures();
        Object name = getObjProperties(student, "name");
        if (name instanceof String) {
            System.out.println((String) name);
        }
//        Object likes = getObjProperties(student, "like");
//        List<String> list = getList(likes);
//        System.out.println(list);
//        System.out.println(getList(getObjProperties(student, "age")));
        Object teatures = getObjProperties(student, "teatures");
        List<Student.Teature> teatureList = getList(teatures);
        System.out.println(teatureList);
    }

    @Data
    static class Student {
        private String name;

        private List<String> like;

        private List<Integer> age;

        private List<Teature> teatures = new ArrayList<>();

        @Data
        class Teature {
            private String name;
            private int age;
        }

        public void setTeatures() {
            Teature teature = new Teature();
            teature.setAge(30);
            teature.setName("xfang");

            Teature teature1 = new Teature();
            teature1.setAge(23);
            teature1.setName("wfang");

            teatures.add(teature);
            teatures.add(teature1);
        }
    }
}
